<?php


namespace App\Models\CacheModel\privatearea;


use App\Models\Api\BaseCache;
use think\Log;
use traits\model\SoftDelete;
use AstroTool\Cache\CacheManage;

class PrivateAreaUserAddress extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.private_area_user_address';

    protected $cacheModel = 'privatearea.mall_address';

    protected $cacheIdKey = 'id';

    use SoftDelete;

    /**
     * 获取地址列表
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getAddressList(int $uid, int $page = 1, int $pageSize = 15): array
    {
        $data = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize($pageSize)
            ->setSort('desc')
            ->setListKeyType(0)
            ->getListPageDataIds(function ($ids = [], $isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $data = $this->where(['uid' => $uid])
                        ->order('is_default desc,id desc')
                        ->column('is_default', 'id');

                    $resData = [];
                    foreach ($data as $id => $isDefault)
                    {
                        $resData[$id] = [
                            'id' => $isDefault ? $id + 10000000 : $id,
                        ];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    $data = [];
                }

                return $data;
            }, 'id');

        $dataLiist = $this->batchGetInfoByIds(array_keys($data['data']));
        $resDataList = [];
        foreach ($data['data'] as $id => $sort)
        {
            if (isset($dataLiist[$id]))
            {
                $resDataList[] = $dataLiist[$id];
            }
        }
        $data['data'] = $resDataList;
        return $data;
    }

    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $where = ['id' => ['in', $ids]];
            } else
            {
                $where = ['uid' => $type[0]];
            }

            $data = $this->where($where)
                ->order('is_default desc,id desc')
                ->column('uid,name,phone,country,province,city,address_desc,is_default,is_faraway,create_time,update_time', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }


    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'is_default', 'is_faraway', 'create_time', 'update_time']);
        }

        return $data;
    }

    public function getPaginateInData($type, $sortType)
    {
        try
        {
            $data = $this->where('uid', $type[0])
                ->order('is_default desc,update_time desc')
                ->field('id,name,phone,country,province,city,address_desc,is_default,is_faraway')
                ->select();

            if ($data)
            {
                $data = collection($data)->toArray();
            }
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return ['data' => $data];
    }

    /**
     * 地址添加或编辑
     * @param int $uid
     * @param int $id
     * @param array $data
     * @return array
     * @throws \Exception
     */
    public function addOrEdir(int $uid, int $id, array $data): array
    {
        // 数据验证
        $mallUserAddressValidate = new \app\common\validate\MallUserAddress();
        $validateRes = $mallUserAddressValidate->check($data);
        if (!$validateRes)
        {
            return [
                'res' => false,
                'msg' => $mallUserAddressValidate->getError(),
            ];
        }
        // 是否是偏远地区
        $data['is_faraway'] = in_array($data['country'], ['内蒙古自治区', '甘肃省', '新疆维吾尔自治区', '西藏自治区', '青海省', '宁夏回族自治区'], true) ? 1 : 0;
        $time = time();
        try
        {
            if ($id)
            {   // 更新
                $d = $this->getInfoById($id, ['uid', 'is_default']);
                if (!$d || $d['uid'] != $uid)
                {
                    return [
                        'res' => false,
                        'msg' => '服务异常，当前地址信息不存在',
                    ];
                }

                if ($data['is_default'] && $d['is_default'] != $data['is_default'])
                {
                    $oldDefaultDataList = $this->where('uid', $uid)->where('is_default', 1)->field('id')->select();
                    if ($oldDefaultDataList)
                    {
                        foreach ($oldDefaultDataList as $oldDefaultData)
                        {
                            $oldDefaultData->is_default = 0;
                            $oldDefaultData->save();

                            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $oldDefaultData->id)->rmCache();
                        }
                    }
                }

                $data['update_time'] = $time;

                $this->save($data, ['id' => $id]);
                $data['id'] = (int)$id;
            } else
            {   // 新增
                $data['uid'] = $uid;
                $data['create_time'] = $time;
                $data['update_time'] = $time;
                if ($data['is_default'])
                {
                    $oldDefaultDataList = $this->where('uid', $uid)->where('is_default', 1)->field('id')->select();
                    if ($oldDefaultDataList)
                    {
                        foreach ($oldDefaultDataList as $oldDefaultData)
                        {
                            $oldDefaultData->is_default = 0;
                            $oldDefaultData->save();

                            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $oldDefaultData->id)->rmCache();
                        }
                    }
                }
                $this->save($data);
                $data['id'] = (int)$this->id;
            }
        }
        catch (\Exception $e)
        {
            Log::write("收货地址添加或更新异常：{$e->getMessage()};错误行数：{$e->getLine()}", 'error', true);
            return [
                'res' => false,
                'msg' => '服务异常，请稍后再试～',
            ];
        }

        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache('list');

        unset($data['create_time'], $data['update_time'], $data['uid']);

        // 成功返回
        return [
            'res' => true,
            'data' => $data,
        ];
    }

    /**
     * 删除收货地址
     * @param int $uid
     * @param int $id
     * @return bool
     */
    public function addressDel(int $uid, int $id): bool
    {
        try
        {
            $res = $this->where('id', $id)->update(['delete_time' => time()]);
            if ($res)
            {   // 删除列表中的数据
                $this->listDataDel($uid, [$id]);
            }

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
            return true;
        }
        catch (\Exception $e)
        {
            Log::write("收货地址删除异常：{$e->getMessage()};错误行数：{$e->getLine()}", 'error', true);
            return false;
        }
    }

    /**
     * 获取用户默认收货地址信息
     * @param int $uid
     * @return array|null
     * @throws \Exception
     */
    public function getDefault(int $uid)
    {
        $data = $this->getAddressList($uid, 1, 5);

        $defaultData = null;
        foreach ($data['data'] as $itemData)
        {
            if ($itemData['is_default'] === 1)
            {
                $defaultData = $itemData;
                break;
            }
        }

        return $defaultData;
    }
}
